import { reqGetAllUser, reqGETUSER } from "@/api/reqUser"
import type { USER } from "@/types/user"
import { computed, ref, watch, watchEffect } from "vue"

export const useShowUser = function () {
  const userListRef = ref<USER[]>([])
  // 获取已有用户
  const getAllUser = async function () {
    const { status, data } = await reqGetAllUser()
    if (status === 0) {
      userListRef.value = data
      // data.forEach(item => userList.push(item))
      // userList.length = 0
    }
  }

  // 翻页当前页
  const nowPageRef = ref(1)
  // 每页的数量
  const sizeRef = ref(5)
  // 总共的数量
  const totalRef = ref(1000)

  watch(totalRef, () => {
    getUserByPage(nowPageRef.value, sizeRef.value)
  })

  // 总共的页数
  // 每页 5个， 6 => 2  10 => 2, 11 => 3
  //  Math.ceil(total/size)
  const totalPageRef = computed(() => {
    return Math.ceil(totalRef.value / sizeRef.value)
  })

  const getUserByPage = async (page: number, size: number) => {
    const { status, data } = await reqGETUSER({ page, size })
    if (status === 0) {
      userListRef.value = data.data
      totalRef.value = data.total
    }
  }

  const sizeChange = (val: number) => {
    sizeRef.value = val
    // getUserByPage(nowPageRef.value, sizeRef.value)
    // getUserByPage()
  }
  const currentChange = (val: number) => {
    nowPageRef.value = val
    // getUserByPage(nowPageRef.value, sizeRef.value)
  }

  watchEffect(() => {
    getUserByPage(nowPageRef.value, sizeRef.value)
  })
  return {
    getAllUser,
    sizeChange,
    currentChange,
    getUserByPage,
    userListRef,
    nowPageRef,
    sizeRef,
    totalRef,
    totalPageRef,
  }
}
